package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.impl.CTUnderlineImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {


    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    @Override
    public TurnoverReportVO turnoverReport(LocalDate beginTime, LocalDate endTime) {

        List<LocalDate> list = new ArrayList<>();
        List<Double> totalAmountList = new ArrayList<>();
        for(LocalDate date = beginTime; date.isBefore(endTime.plusDays(1)); date = date.plusDays(1)) {
            list.add(date);

            LocalDateTime localDateTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime localDateTime1 = LocalDateTime.of(date, LocalTime.MAX);

            //查询当天的订单总金额
            Map map = new HashMap();
            map.put("beginTime", localDateTime);
            map.put("endTime", localDateTime1);
            map.put("status", Orders.COMPLETED);
            Double totalAmount = orderMapper.selectTotalAmount(map);
            if (totalAmount == null) {
                totalAmount = 0.0;
            }

            totalAmountList.add(totalAmount);


        }



        TurnoverReportVO turnoverReportVO = new TurnoverReportVO();
        turnoverReportVO.setDateList(StringUtils.join(list, ","));
        turnoverReportVO.setTurnoverList(StringUtils.join(totalAmountList, ","));

        return turnoverReportVO;

    }

    @Override
    public UserReportVO userReport(LocalDate begin, LocalDate end) {

        List<LocalDate> list = new ArrayList<>();
        List<Integer> newUserList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();


        for (LocalDate date = begin; date.isBefore(end.plusDays(1)); date = date.plusDays(1)) {
            list.add(date);

            LocalDateTime localDateTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime localDateTime1 = LocalDateTime.of(date, LocalTime.MAX);

            //查询当天新增用户数
            Integer newUser = userMapper.selectUser(localDateTime, localDateTime1);
            if (newUser == null) {
                newUser = 0;
            }
            newUserList.add(newUser);

            //查询当天总用户数
            Integer totalUser = userMapper.selectUser(null,localDateTime1);
            if (totalUser == null) {
                totalUser = 0;
            }
            totalUserList.add(totalUser);

        }

        UserReportVO userReportVO = new UserReportVO();
        userReportVO.setDateList(StringUtils.join(list, ","));
        userReportVO.setNewUserList(StringUtils.join(newUserList, ","));
        userReportVO.setTotalUserList(StringUtils.join(totalUserList, ","));
        return userReportVO;
    }

    @Override
    public OrderReportVO orderReport(LocalDate begin, LocalDate end) {

        List<LocalDate> list = new ArrayList<>();
        List<Integer> completedList = new ArrayList<>();
        List<Integer> totalList = new ArrayList<>();

        for (LocalDate date = begin; date.isBefore(end.plusDays(1)); date = date.plusDays(1)) {
            list.add(date);

            LocalDateTime localDateTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime localDateTime1 = LocalDateTime.of(date, LocalTime.MAX);

            //查询当天已完成订单数
            Integer completed = orderMapper.countByStatusAndOrderTime(Orders.COMPLETED, localDateTime, localDateTime1);
            if (completed == null) {
                completed = 0;
            }
            completedList.add(completed);

            //查询当天总订单数
            Integer total = orderMapper.countByStatusAndOrderTime(null, localDateTime, localDateTime1);
            if (total == null) {
                total = 0;
            }
            totalList.add(total);
        }

        Integer total = totalList.stream().mapToInt(Integer::intValue).sum();
        if (total == null) {
            total = 0;
        }
        Integer completed = completedList.stream().mapToInt(Integer::intValue).sum();
        if (completed == null) {
            completed = 0;
        }
        Double rate = total == 0 ? 0 : completed * 1.0 / total;

        OrderReportVO orderReportVO = new OrderReportVO();

        orderReportVO.setDateList(StringUtils.join(list, ","));

        orderReportVO.setOrderCompletionRate(rate);

        orderReportVO.setOrderCountList(StringUtils.join(totalList, ","));

        orderReportVO.setValidOrderCountList(StringUtils.join(completedList, ","));

        orderReportVO.setValidOrderCount(completed);

        orderReportVO.setTotalOrderCount(total);

        return orderReportVO;

    }

    @Override
    public SalesTop10ReportVO top10Report(LocalDate begin, LocalDate end) {

        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        List<GoodsSalesDTO> goodsSalesDTOList = orderMapper.goodsSales(beginTime, endTime);

        SalesTop10ReportVO salesTop10ReportVO = new SalesTop10ReportVO();

        List<String> nameList = goodsSalesDTOList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> salesList = goodsSalesDTOList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        salesTop10ReportVO.setNameList(StringUtils.join(nameList, ","));
        salesTop10ReportVO.setNumberList(StringUtils.join(salesList, ","));

        return salesTop10ReportVO;

    }

    @Override
    public void export(HttpServletResponse response) throws IOException {
        //查询数据
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(dateBegin, LocalTime.MIN), LocalDateTime.of(dateEnd, LocalTime.MAX));

        //通过POI导出数据
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("Template/运营数据报表模板.xlsx");
        XSSFWorkbook workbook = new XSSFWorkbook(resourceAsStream);

        //导出数据
        XSSFSheet sheet1 = workbook.getSheet("sheet1");

        sheet1.getRow(1).getCell(1).setCellValue("时间：" + dateBegin + "至" + dateEnd);

        //第四行
        XSSFRow row = sheet1.getRow(3);
        row.getCell(2).setCellValue(businessData.getTurnover());
        row.getCell(4).setCellValue(businessData.getValidOrderCount());
        row.getCell(6).setCellValue(businessData.getNewUsers());
        //第五行
        row = sheet1.getRow(4);
        row.getCell(2).setCellValue(businessData.getValidOrderCount());
        row.getCell(4).setCellValue(businessData.getUnitPrice());

        for(int i = 0; i < 30; i++) {
            LocalDate date = dateBegin.plusDays(i);
            BusinessDataVO businessData1 = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

            row = sheet1.getRow(7 + i);
            row.getCell(1).setCellValue(date.toString());
            row.getCell(2).setCellValue(businessData1.getTurnover());
            row.getCell(3).setCellValue(businessData1.getValidOrderCount());
            row.getCell(4).setCellValue(businessData1.getOrderCompletionRate());
            row.getCell(5).setCellValue(businessData1.getUnitPrice());
            row.getCell(6).setCellValue(businessData1.getNewUsers());

        }

        //导出
        ServletOutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);
        workbook.close();
        outputStream.close();

    }
}
